import { message } from 'antd';

// 获取基础URL
const getBaseURL = () => {
  const protocol = window.location.protocol;
  const host = window.location.host.includes('pre-')
    ? 'pre-api.woniutech.com'
    : 'api.woniutech.com';
  return `${protocol}//${host}`;
};

// 获取Authorization
const getAuthorization = () => {
  return localStorage.getItem('Authorization') || '';
};

// 统一请求处理
export const request = async <T = any>(
  url: string,
  options: RequestInit = {}
): Promise<T> => {
  const baseURL = getBaseURL();
  const Authorization = getAuthorization();

  // 默认请求头
  const defaultHeaders: HeadersInit = {
    'Content-Type': 'application/json',
    'Authorization': Authorization,
  };

  // 合并请求头
  const headers = {
    ...defaultHeaders,
    ...options.headers,
  };

  try {
    const response = await fetch(`${baseURL}${url}`, {
      ...options,
      headers,
    });

    // 处理401未授权
    if (response.status === 401) {
      message.error('登录已过期，请重新登录');
      // 清除本地存储的token
      localStorage.removeItem('Authorization');
      // 跳转到登录页
      window.location.href = '/login';
      throw new Error('UNAUTHORIZED');
    }

    // 处理其他HTTP错误
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    
    // 处理业务错误
    if (!data.success) {
      message.error(data.errorMsg || '请求失败');
      throw new Error(data.errorMsg || '请求失败');
    }

    return data.data;
  } catch (error) {
    if (error instanceof Error) {
      if (error.message === 'UNAUTHORIZED') {
        throw error;
      }
      message.error(error.message || '网络异常，请稍后重试');
    } else {
      message.error('网络异常，请稍后重试');
    }
    throw error;
  }
};

// 获取完整响应的请求方法
export const requestWithResponse = async <T = any>(
  url: string,
  options: RequestInit = {}
): Promise<T> => {
  const baseURL = getBaseURL();
  const Authorization = getAuthorization();

  const defaultHeaders: HeadersInit = {
    'Content-Type': 'application/json',
    'Authorization': Authorization,
  };

  const headers = {
    ...defaultHeaders,
    ...options.headers,
  };

  try {
    const response = await fetch(`${baseURL}${url}`, {
      ...options,
      headers,
    });

    if (response.status === 401) {
      message.error('登录已过期，请重新登录');
      localStorage.removeItem('Authorization');
      window.location.href = '/login';
      throw new Error('UNAUTHORIZED');
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    if (error instanceof Error) {
      if (error.message === 'UNAUTHORIZED') {
        throw error;
      }
      message.error(error.message || '网络异常，请稍后重试');
    } else {
      message.error('网络异常，请稍后重试');
    }
    throw error;
  }
};

// GET请求
export const get = <T = any>(url: string, params?: Record<string, any>) => {
  const queryString = params ? new URLSearchParams(params).toString() : '';
  const fullUrl = queryString ? `${url}?${queryString}` : url;
  return request<T>(fullUrl);
};

// POST请求
export const post = <T = any>(url: string, data?: any) => {
  return request<T>(url, {
    method: 'POST',
    body: JSON.stringify(data),
  });
};

// 需要完整响应的POST请求
export const postWithResponse = <T = any>(url: string, data?: any) => {
  return requestWithResponse<T>(url, {
    method: 'POST',
    body: JSON.stringify(data),
  });
};

// PUT请求
export const put = <T = any>(url: string, data?: any) => {
  return request<T>(url, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
};

// DELETE请求
export const del = <T = any>(url: string, data?: any) => {
  return request<T>(url, {
    method: 'DELETE',
    body: JSON.stringify(data),
  });
}; 